package com.ddc.study.base;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.ArrayMap;

import com.ddc.study.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 * Created on 2018/8/3.
 *
 * @author lshun
 * @version 1.0
 */
public class CookieManager implements CookieJar {
    private static final String TAG = "CookieManager";
    private static final String PREFS_KEY = "CookiePrefs";

    private Context mContext;
    private Map<String, Cookie> mCookieMap;

    CookieManager(Context context) {
        mContext = context;

        mCookieMap = new ArrayMap<>();

        SharedPreferences sp = mContext.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
        Map<String, ?> map = sp.getAll();
        for (Map.Entry<String, ?> entry : map.entrySet()) {
            Cookie cookie = parseCookie((String) entry.getValue());
            if (cookie != null) {
                mCookieMap.put(cookie.name(), cookie);
            }
        }
    }

    /**
     * 注销登录 清除cookie
     */
    public void logOut() {
        mCookieMap.clear();
        mContext.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE).edit().clear().apply();
    }

    @Override
    public void saveFromResponse(@NonNull HttpUrl url, @NonNull List<Cookie> cookies) {
        Log.e(TAG, url + " save cookies -> " + cookies);

        for (Cookie cookie : cookies) {
            if (!"JSESSIONID".equals(cookie.name()))
                mCookieMap.put(cookie.name(), cookie);
        }

        //TODO 优化 -> APP退出时候存储到本地
        //Cookie持久化
        SharedPreferences sp = mContext.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        for (Map.Entry<String, Cookie> entry : mCookieMap.entrySet()) {
            editor.putString(entry.getKey(), decodeCookie(entry.getValue()));
        }
        editor.apply();
    }

    @NonNull
    @Override
    public List<Cookie> loadForRequest(@NonNull HttpUrl url) {
        List<Cookie> cookies = new ArrayList<>(mCookieMap.values());
        Log.e(TAG, url + " get cookies -> " + cookies);
        return cookies;

//        return new ArrayList<>(mCookieMap.values());
    }

    /**
     * 将字符串解析成cookie
     *
     * @return 解析失败时返回null
     */
    @Nullable
    private Cookie parseCookie(String setCookie) {
        if (setCookie == null) return null;

        //解析cookie
        String[] data = setCookie.split(";");

        if (data.length != 9) return null;

        String name = data[0];
        String value = data[1];
        long expiresAt = Long.valueOf(data[2]);
        String domain = data[3];
        String path = data[4];
        boolean secure = Boolean.valueOf(data[5]);
        boolean httpOnly = Boolean.valueOf(data[6]);
        boolean hostOnly = Boolean.valueOf(data[7]);
        boolean persistent = Boolean.valueOf(data[8]);

        Cookie.Builder builder = new Cookie.Builder();
        builder.name(name)
                .value(value)
                .path(path);

        if (secure) builder.secure();
        if (httpOnly) builder.httpOnly();

        if (hostOnly) {
            builder.hostOnlyDomain(domain);
        } else {
            builder.domain(domain);
        }

        if (persistent) builder.expiresAt(expiresAt);

        return builder.build();
    }

    private String decodeCookie(Cookie cookie) {
        return cookie.name() + ";" + cookie.value() + ";" + cookie.expiresAt() + ";" +
                cookie.domain() + ";" + cookie.path() + ";" + cookie.secure() + ";" +
                cookie.httpOnly() + ";" + cookie.hostOnly() + ";" + cookie.persistent();
    }
}
